# 参考：https://stackoverflow.com/questions/16056793/python-win32com-client-dispatch-looping-through-word-documents-and-export-to-pdf

import os
import os.path
from win32com import client as wc
import PySimpleGUI as sg


def get_names(folder_path, ext='.ppt', new_ext = '.pptx'):
    names = [name for name in os.listdir(folder_path)
             if os.path.isfile(os.path.join(folder_path, name)) and name.endswith(ext)]
    # 老文件名路径，含扩展名
    oldnames_fullpath = [os.path.join(folder_path, name) for name in names]
    # 老文件名路径，不含扩展名
    oldnames_fullpath_withoutext = [os.path.splitext(oldname_path)[0] for oldname_path in oldnames_fullpath]

    # 新文件名路径，含扩展名
    newnames_fullpath = [name_without_ext + new_ext for name_without_ext in oldnames_fullpath_withoutext]

    # 总文件数
    cnt = len(oldnames_fullpath)
    # 新旧文件对
    old_new_pair = zip(oldnames_fullpath, newnames_fullpath)
    return old_new_pair, cnt

# 输出格式： https://docs.microsoft.com/en-us/previous-versions/office/developer/office-2010/ff760025(v=office.14)?redirectedfrom=MSDN
def TransBatch(folder_path, window, out_format_number = 11, ext='.ppt', new_ext='.pptx'):
    old_new_pairs, total_cnt = get_names(folder_path, ext, new_ext)
    powerpoint = wc.DispatchEx('Powerpoint.Application')
    # powerpoint.Visible = False 会报pywintypes.com_error: 'Application.Visible : Invalid request. Hiding the application window is not allowed的错误
    for index, pair in enumerate(old_new_pairs):
        old_file, new_file = pair[0], pair[1]
        print(old_file, new_file)
        # 打开旧ppt文件
        doc = powerpoint.Presentations.Open(old_file, WithWindow=False) #WithWindow=False用于不显示PowerPoint窗口
        # 保存为 新文件,其中参数 11表示的是pptx文件, 32表示pdf文件
        doc.SaveAs(new_file, out_format_number)
        # 关闭文档
        doc.Close()
        # print(f"{new_file} 生成完毕！")
        window['-OUT-'].update(f"第{index+1}/{total_cnt}个文件生成完毕！")
        window.refresh()
    powerpoint.Quit()
    window.write_event_value('-DONE-', '')

if __name__ == "__main__":

    out_format = {'pptx':11, 'pdf': 32} # ppSaveAsXMLPresentation or pdf
    out_ext ={11:'.pptx', 32:'.pdf'}
    sg.theme('Dark Grey 13')

    layout = [[sg.Text('请输入文件夹名称（包含doc文档）')],
              [sg.Input(key='-IN-'), sg.Button('Convert')],
              [sg.Radio('TO PPTX', 'FORMAT', key='pptx', default=True, enable_events=True, size=(10, 1)),
               sg.Radio('TO PDF', 'FORMAT', key='pdf', enable_events=True, size=(10, 1))],
              [sg.Text(key='-OUT-')]
             ]

    window = sg.Window('批量ppt转为pptx,pdf', layout)
    while True:
        event, values = window.read()
        if event == sg.WINDOW_CLOSED:
            break
        elif event == 'Convert':
            folder_path = values['-IN-']
            if len(folder_path) == 0:
                sg.popup('温馨提示', '请输入文件夹名称', values['-IN-'])
            else:
                out_format_number = out_format['pptx'] if values['pptx'] else out_format['pdf']
                TransBatch(folder_path, window, out_format_number, ext='.ppt', new_ext=out_ext[out_format_number] )
        elif event == '-DONE-':
            window['-OUT-'].update('转换完毕！')
            window.refresh()
        # print(values)
    window.close()

